<template>
  	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="120px">
			<el-form-item label="时间筛选：">
				<span class="label-left">支付</span>
				<el-date-picker
					v-model="payRange"
					type="datetimerange"
					value-format="yyyy-MM-dd HH:mm:ss"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					:default-time="['00:00:00', '23:59:59']"
					align="right">
				</el-date-picker>
				<span class="label-last">加微</span>
				<el-date-picker
					v-model="dateRange"
					type="datetimerange"
					value-format="yyyy-MM-dd HH:mm:ss"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					:default-time="['00:00:00', '23:59:59']"
					align="right">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="基础信息：">
				<el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
				<el-select v-model="queryParams.user_ids" placeholder="请选择社群老师" multiple filterable clearable >
					<el-option v-for="item in teacherList" :key="item.wx_user_id" :label="item.name" :value="item.wx_user_id" />
				</el-select>
				<el-select v-model="queryParams.is_wechat" placeholder="加微状态选择" clearable style="width: 240px">
					<el-option label="全部" value="" />
					<el-option label="未加微" value="0" />
					<el-option label="已加微" value="1" />
				</el-select>
				<el-select v-model="queryParams.pay_amount" placeholder="请选择价格" clearable style="width: 160px">
					<el-option label="全部" value="" />
					<el-option v-for="item in priceList" :key="item" :label="item" :value="item" />
				</el-select>
			</el-form-item>
			<el-form-item label="用户标签筛选：">
				<el-select v-model="queryParams.sex" placeholder="请选择性别" clearable >
					<el-option v-for="item in sexList" :key="item.id" :label="item.title" :value="item.id" />
				</el-select>
				<el-select v-model="queryParams.ages" placeholder="请选择年龄" clearable multiple>
					<el-option v-for="item in agesList" :key="item.id" :label="item.title" :value="item.id" />
				</el-select>
				<el-cascader v-model="tagsSearch" placeholder="请选择召回标签" :props="props" style="width: 280px" collapse-tags :options="tagsOptions" @change="tagsChange" />
		
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		<el-table v-loading="loading" :data="saleList">
			<el-table-column label="用户手机号" align="center" prop="external_phone"  width="150" fixed="left">
              <template slot-scope="scope">
                  <span>{{ scope.row.external_phone }}</span>
                  <el-button type="text" icon="el-icon-edit" @click="openSingle(scope.row)" />
              </template>
          	</el-table-column>
			<el-table-column label="用户昵称" align="center" prop="customer_name" min-width="120" :show-overflow-tooltip="true" />
			<el-table-column label="社群老师" align="center" prop="name" min-width="120" :show-overflow-tooltip="true" />
			<el-table-column label="社群老师ID" align="center" prop="wechat_user_id" min-width="180" :show-overflow-tooltip="true" />
			<el-table-column label="支付时间" align="center" prop="pay_time" width="180" />
			<el-table-column label="加微时间" align="center" prop="wechat_time" width="180" />
			<el-table-column label="价格" align="center" prop="pay_amount" width="90" />
			<el-table-column label="加微状态" align="center" prop="is_wechat" width="90">
				<template slot-scope="scope">
					<el-tag type="success" v-if="scope.row.is_wechat == '1'">已加微</el-tag>
					<el-tag type="danger" v-else>未加微</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="性别" align="center" prop="sex" width="90" />
			<el-table-column label="年龄" align="center" prop="age" width="90" />
			<el-table-column label="召回标签" align="center" prop="tag" width="150" :show-overflow-tooltip="true" />
			
			<el-table-column label="操作" align="center" width="360"  fixed="right">
				<template slot-scope="scope">
					<el-button size="mini" :disabled="scope.row.class_is_wechat == '1'" type="primary" @click="handleUpdate(scope.row.code)">标记为已加微</el-button>
					<el-button size="mini" :disabled="scope.row.class_is_wechat == '1' || scope.row.lock || scope.row.external_phone == ''"  type="primary" icon="el-icon-message" @click="handleSms(scope.row)">发送短信</el-button>
					<el-button size="mini"  type="primary" @click="editUser(scope.row)">用户标记</el-button>
				</template>
			</el-table-column>
      	</el-table>

  		<pagination
			v-show="total>0"
			:total="total"
			:page.sync="queryParams.page"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 修改手机号对话框 -->
		<el-dialog :visible.sync="showPhone" width="300px" top="30vh">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm">
				<el-form-item prop="newPhone">
					<el-input v-model.number="ruleForm.newPhone" type="tel" placeholder="请输入手机号" />
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showPhone = false">取 消</el-button>
				<el-button type="primary" @click="updatePhone">确 认</el-button>
			</span>
		</el-dialog>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog title="用户标记" :visible.sync="showDialog" width="600px">
			<el-form ref="userForm" :model="userForm" label-width="120px">
				<el-form-item label="用户手机号">
					<label>{{ userForm.class_external_phone }}</label>
				</el-form-item>
				<el-form-item label="用户昵称">
					<label>{{ userForm.customer_name}}</label>
				</el-form-item>

				<el-form-item label="性别" prop="sex">
					<el-radio-group v-model="userForm.sex">
						<el-radio v-for="item in testList" :key="item.id" :label="item.id">{{ item.title }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-radio-group v-model="userForm.age">
						<el-radio v-for="item in agesList" :key="item.id" :label="item.id">{{ item.title }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="召回标记" prop="tagVal">
					<el-cascader v-model="userForm.tagVal" placeholder="请选择召回标签" style="width: 280px" :options="tagsOptions" @change="tagsChangeUser" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="showDialog = false;">取 消</el-button>
			</div>
		</el-dialog>
  	</div>
</template>

<script>
import { getTeacher, getPriceList, getSex, getAges, getBackTags, listSale, recall, sendSms, updateOrder, updatePhone } from "@/api/sale";

const checkPhone = (rule, value, callback) => {
	const regPhone = /^1[3|4|5|6|7|8|9][0-9]{9}$/
	if (value === '') {
		return callback(new Error('手机号不能为空'))
	} else if (!regPhone.test(value)) {
		callback(new Error('请输入正确的手机号'))
	} else {
		callback()
	}
};
export default {
	data() {
		return {
			loading: true,	// 遮罩层
			showSearch: true,// 显示搜索条件
			teacherList:[],
			priceList:[],//下拉价格
			sexList:[],
			agesList:[],
			queryParams: { 	// 查询参数
				page: 1,
				pageSize: 20,
				name: undefined,
				phone: undefined,
				is_wechat: undefined,
			},
			payRange:[],
			dateRange: [],
			saleList:[],
			total:0,
			props: { multiple: true,expandTrigger: 'hover' },
			tagsOptions: [],
			tagsList:[],
			tagsSearch:[],
			showPhone: false,
			checkedUser:{},
			ruleForm: {},
			rules: {newPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' },{ validator: checkPhone, trigger: 'blur' }]},
			showDialog:false,
			userForm:{},
			testList:[]
		};
	},
	created() {
		this.getPriceList()
		this.getTeacherList()
		this.getSexList();
		this.getAgesList();
		this.getBackTagsList();
		this.getList();
	},
  	methods: {
		getPriceList(){
			getPriceList().then(res => {
				this.priceList = res.data
			});
		},
		getSexList(){
			getSex().then(res => {
				this.sexList = res.data
				this.testList = res.data
			})
		},
		getAgesList(){
			getAges().then(res => {
				this.agesList = res.data
			})
		},
		getTeacherList(){
			getTeacher().then(res => {
				this.teacherList = res.data
			});
		},
		getBackTagsList(){
			getBackTags().then(res => {
				this.tagsOptions = res.data
				this.tagsOptions.forEach(item => {
					this.tagsList = [...item.children,...this.tagsList]
				})
			})
		},
		openSingle(rows){
			this.ruleForm = {newPhone: rows.external_phone}
			this.showPhone = true
			this.checkedUser = rows
		},
		updatePhone(){
			this.$refs["ruleForm"].validate(valid => {
				if (valid) {
					const params = {
						id: this.checkedUser.id,
						phone: this.ruleForm.newPhone
					}
					updatePhone(params).then(res => {
						this.$modal.msgSuccess("修改成功");
						this.showPhone = false;
						this.getList();
					})
				}
			})
		
		},
		tagsChange(value) {
			let tags = []
			value.forEach(item => {
				let index = this.tagsList.find(item2 => item[1] == item2.value)
				tags.push(index.label)
			})
			this.queryParams.tags = tags
		},
      	getList() {
			this.loading = true;

			//加微时间处理
			this.dateRange = Array.isArray(this.dateRange) ? this.dateRange : [];
			this.queryParams.wechat_time_start = this.dateRange[0];
    		this.queryParams.wechat_time_end = this.dateRange[1];

			//支付时间处理
			this.payRange = Array.isArray(this.payRange) ? this.payRange : [];
			this.queryParams.pay_start_time = this.payRange[0];
    		this.queryParams.pay_end_time = this.payRange[1];

			listSale(this.queryParams).then(res => {
				this.saleList = res.data.data
				this.saleList.forEach(item => {
					item.lock = false
				})
				this.total = res.data.total;
				this.loading = false;
			});
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.page = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryParams");
			this.dateRange = []
			this.payRange = []
			this.tagsSearch = []
			this.queryParams = {
				page: 1,
				pageSize: 20
			}
			this.handleQuery();
		},
		handleUpdate(code){
			recall({code:code}).then(res => {
				this.$modal.msgSuccess("加微状态修改成功");
				this.getList();
			});
		},
		handleSms(obj){
			if(obj.lock) return false
			const params = {
				"order_code": obj.code,
				"prodcut_id": obj.product_id,
				"wx_user_id": obj.wechat_user_id
			}
			this.$modal.confirm('是否向手机号为：' + obj.external_phone + '的用户发送短信？').then(function(){
				return sendSms(params);
			}).then(() => {
				this.saleList[index].lock = true
				this.$modal.msgSuccess("发送成功");
			}).catch(() => {});
		},
		editUser(rows){
			let obj = {}, arr = [], pID = 1
			obj = {
				class_id: rows.id,
				class_external_phone: rows.external_phone,
				customer_name: rows.customer_name
			}
			
			//转义回显性别
			if(rows.sex && rows.sex !== ''){
				let sex = this.sexList.find(item => item.title == rows.sex)
				obj.sex = sex.id
			}
			
			//转义回显年龄
			if(rows.age && rows.age !== ''){
				let age = this.agesList.find(item => item.title == rows.age)
				obj.age = age.id
			}
			
			//转义回显tag
			if(rows.tag !== ''){
				this.tagsOptions.forEach(item => {
					arr = [...arr,...item.children]
				})
				let index = arr.find(item => item.label == rows.tag)
				pID = Math.floor(index.value / 10)
				obj.tagVal = [pID,index.value]
				obj.tag = rows.tag
			}
			this.userForm = obj
			this.showDialog = true
		},
		tagsChangeUser(val){
			let tagsParen = this.tagsOptions.find(item => item.value == val[0])
			let tagsChild = tagsParen.children.find(item => item.value == val[1])
			this.userForm.tag = tagsChild.label
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["userForm"].validate(valid => {
				if (valid) {
					const params = {
						"id": this.userForm.class_id, 
						"sex": this.userForm.sex, 
						"age": this.userForm.age, 
						"tag": this.userForm.tag 
					}	
					updateOrder(params).then(res => {
						this.$modal.msgSuccess("修改成功");
						this.showDialog = false;
						this.getList();
					});
				}
			});
		},
	}
};
</script>

<style scoped>
	.label-left{display: inline-block;margin-right: 10px;}
	.label-last{display: inline-block;margin-left: 25px;margin-right: 10px;}
	.el-input,
	.el-select,
	.el-cascader{margin-right: 20px;}
</style>

<style>
.el-radio input[aria-hidden="true"]{display: none!important;}
</style>